﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Pomelo.DotNetClient;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NetManager
{
    // Start is called before the first frame update
    string host = "127.0.0.1";//(www.xxx.com/127.0.0.1/::1/localhost etc.)
    int port = 3010;
    PomeloClient pclient = new PomeloClient();

    public NetManager()
    {
        pclient.NetWorkStateChangedEvent += (state) =>
        {
            Debug.Log("state changed " + state);
        };

    }
    //listen on network state changed event

    private void OnAdd(JObject Msg)
    {
        Debug.Log("OnAdd : " + Msg.ToString());
    }

    public void QueryEntry()
    {
        pclient.initClient(host, port, () =>
        {
            Debug.Log("pc.initClient callback.");
            JObject user = JObject.Parse("{}");
            pclient.connect(user, (data) =>
            {
                Debug.Log("pc.connect callback.");
                var route = "gate.gateHandler.queryEntry";
                JObject msg = new JObject();
                msg["uid"] = "test";
                pclient.request(route, msg, OnQueryEntry);
            });

        });
    }

    void OnInit()
    {
        pclient.on("onAdd", OnAdd);
    }

    void OnQueryEntry(JObject result)
    {
        if (Convert.ToInt32(result["code"]) == 200)
        {
            pclient.disconnect();
            string host = (string)result["host"];
            int port = Convert.ToInt32(result["port"]);
            pclient = new PomeloClient();
            pclient.initClient(host, port, () =>
            {
                pclient.connect((data) =>
                {
                    Debug.Log("OnQueryEntry successful");
                    JoinRoom("Birkhoff", "yyjjk");
                });
            });
        }
    }

    void JoinRoom(string NickName, String RoomName)
    {
        JObject userMessage =  JObject.Parse("{}");
        userMessage.Add("username", NickName);
        userMessage.Add("rid", RoomName);
        if (pclient != null)
        {
            pclient.request("connector.entryHandler.enter", userMessage, OnJoinRoom);
        }
    }

    void OnJoinRoom(JObject data)
    {
        UserList userList = data.ToObject<UserList>(); //JsonConvert.DeserializeObject<UserList>();
        Debug.Log("JoinRoom successful");
    }
}